<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>vue计算属性与数据监听（十） | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Vue,">
  

  <meta name="description" content="一、监听属性 我们在工作中常常需要监听某一个属性值的变化，这个时候我们就需要用到了监听属性watch  1.1 基础版监听 场景如下：输入框输入你的年龄，如果年龄在0-15岁提示信息：你还是个小孩，如果年龄在 15-25岁，提示信息：你已经是个少年，如果年龄在25岁以上，提示信息：你已经长大了  &amp;lt;template&amp;gt; &amp;lt;div id=&quot;app&quot;&amp;gt;  年齡：&amp;lt;input">
<meta name="keywords" content="Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="vue计算属性与数据监听（十）">
<meta property="og:url" content="http://blog.poetries.top/2018/08/28/vue-computed-watch/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、监听属性 我们在工作中常常需要监听某一个属性值的变化，这个时候我们就需要用到了监听属性watch  1.1 基础版监听 场景如下：输入框输入你的年龄，如果年龄在0-15岁提示信息：你还是个小孩，如果年龄在 15-25岁，提示信息：你已经是个少年，如果年龄在25岁以上，提示信息：你已经长大了  &amp;lt;template&amp;gt; &amp;lt;div id=&quot;app&quot;&amp;gt;  年齡：&amp;lt;input">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.938Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue计算属性与数据监听（十）">
<meta name="twitter:description" content="一、监听属性 我们在工作中常常需要监听某一个属性值的变化，这个时候我们就需要用到了监听属性watch  1.1 基础版监听 场景如下：输入框输入你的年龄，如果年龄在0-15岁提示信息：你还是个小孩，如果年龄在 15-25岁，提示信息：你已经是个少年，如果年龄在25岁以上，提示信息：你已经长大了  &amp;lt;template&amp;gt; &amp;lt;div id=&quot;app&quot;&amp;gt;  年齡：&amp;lt;input">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、监听属性"><span class="toc-text">一、监听属性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-基础版监听"><span class="toc-text">1.1 基础版监听</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-进阶版监听"><span class="toc-text">1.2 进阶版监听</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-高级版监听"><span class="toc-text">1.3 高级版监听</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、计算属性"><span class="toc-text">二、计算属性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-什么是计算属性"><span class="toc-text">2.1 什么是计算属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-计算属性的用法"><span class="toc-text">2.2 计算属性的用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-计算属性缓存"><span class="toc-text">2.3 计算属性缓存</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-vue-computed-watch" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">vue计算属性与数据监听（十）</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.08.28</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 8分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、监听属性"><a href="#一、监听属性" class="headerlink" title="一、监听属性"></a>一、监听属性</h2><blockquote>
<p>我们在工作中常常需要监听某一个属性值的变化，这个时候我们就需要用到了监听属性<code>watch</code></p>
</blockquote>
<h3 id="1-1-基础版监听"><a href="#1-1-基础版监听" class="headerlink" title="1.1 基础版监听"></a>1.1 基础版监听</h3><blockquote>
<p>场景如下：输入框输入你的年龄，如果年龄在0-15岁提示信息：你还是个小孩，如果年龄在 15-25岁，提示信息：你已经是个少年，如果年龄在25岁以上，提示信息：你已经长大了</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">  年齡：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"number"</span> <span class="attr">v-model</span>=<span class="string">"age"</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">  提示信息：<span class="tag">&lt;<span class="name">span</span>&gt;</span>&#123;&#123;infoMsg&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"> data() &#123;</span><br><span class="line"><span class="javascript">  <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="javascript">   age: <span class="string">""</span>,</span></span><br><span class="line"><span class="javascript">   infoMsg:<span class="string">""</span></span></span><br><span class="line">  &#125;</span><br><span class="line"> &#125;,</span><br><span class="line"> watch:&#123;</span><br><span class="line"><span class="javascript">  age:<span class="function"><span class="keyword">function</span>(<span class="params">val,oldval</span>)</span>&#123;</span></span><br><span class="line">   if(val&gt;0 &amp;&amp; val&lt;15)&#123;</span><br><span class="line"><span class="javascript">    <span class="keyword">this</span>.infoMsg=<span class="string">"你还是个小孩"</span></span></span><br><span class="line"><span class="javascript">   &#125;<span class="keyword">else</span> <span class="keyword">if</span>(val&gt;<span class="number">15</span> &amp;&amp; val&lt;<span class="number">25</span>)&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">this</span>.infoMsg=<span class="string">"你已经是个少年"</span></span></span><br><span class="line"><span class="javascript">   &#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">this</span>.infoMsg=<span class="string">"你已经长大了"</span></span></span><br><span class="line">   &#125;</span><br><span class="line">  &#125;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="1-2-进阶版监听"><a href="#1-2-进阶版监听" class="headerlink" title="1.2 进阶版监听"></a>1.2 进阶版监听</h3><blockquote>
<p>下面我们改变一下需求：基础规则不变，但是因为后台数据库的更改,我们需要提交一个这样的数据结构</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">data() &#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">   info: &#123;</span><br><span class="line">    age: <span class="string">""</span></span><br><span class="line">   &#125;,</span><br><span class="line">   infoMsg: <span class="string">""</span></span><br><span class="line">  &#125;;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>由于我们监听的是对象<code>info</code>中的属性<code>age</code>值的变化，所以我们需要使用到的是深度监听，具体代码如下</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">  年齡：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"number"</span> <span class="attr">v-model</span>=<span class="string">"info.age"</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">  提示信息：<span class="tag">&lt;<span class="name">span</span>&gt;</span>&#123;&#123;infoMsg&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"> data() &#123;</span><br><span class="line"><span class="javascript">  <span class="keyword">return</span> &#123;</span></span><br><span class="line">   info: &#123;</span><br><span class="line"><span class="javascript">    age: <span class="string">""</span></span></span><br><span class="line">   &#125;,</span><br><span class="line"><span class="javascript">   infoMsg: <span class="string">""</span></span></span><br><span class="line">  &#125;;</span><br><span class="line"> &#125;,</span><br><span class="line"> watch: &#123;</span><br><span class="line">  info: &#123;</span><br><span class="line"><span class="javascript">   handler: <span class="function"><span class="keyword">function</span>(<span class="params">val, oldval</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> that = <span class="keyword">this</span>;</span></span><br><span class="line">    if (val.age &gt; 0 &amp;&amp; val.age &lt; 15) &#123;</span><br><span class="line"><span class="javascript">     that.infoMsg = <span class="string">"你还是个小孩"</span>;</span></span><br><span class="line"><span class="javascript">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (val.age &gt; <span class="number">15</span> &amp;&amp; val.age &lt; <span class="number">25</span>) &#123;</span></span><br><span class="line"><span class="javascript">     that.infoMsg = <span class="string">"你已经是个少年"</span>;</span></span><br><span class="line"><span class="javascript">    &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">     that.infoMsg = <span class="string">"你已经长大了"</span>;</span></span><br><span class="line">    &#125;</span><br><span class="line">   &#125;,</span><br><span class="line"><span class="javascript">   deep: <span class="literal">true</span></span></span><br><span class="line">  &#125;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>这里的<code>function</code>不能使用箭头函数替代，如果使用箭头函数的话，<code>this</code>的指向会是全局</li>
<li>你会注意到这里多加入一个属性是<code>deep</code>，它的含义表示是否开启深度监听，如果开启值为<code>true</code>，反之为<code>false</code></li>
</ul>
<h3 id="1-3-高级版监听"><a href="#1-3-高级版监听" class="headerlink" title="1.3 高级版监听"></a>1.3 高级版监听</h3><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">  年齡：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"number"</span> <span class="attr">v-model</span>=<span class="string">"info.age"</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">  提示信息：<span class="tag">&lt;<span class="name">span</span>&gt;</span>&#123;&#123;infoMsg&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"> data() &#123;</span><br><span class="line"><span class="javascript">  <span class="keyword">return</span> &#123;</span></span><br><span class="line">   info: &#123;</span><br><span class="line"><span class="javascript">    age: <span class="string">""</span>,</span></span><br><span class="line"><span class="javascript">    name: <span class="string">""</span>,</span></span><br><span class="line"><span class="javascript">    hobit: <span class="string">""</span></span></span><br><span class="line">   &#125;,</span><br><span class="line"><span class="javascript">   infoMsg: <span class="string">""</span></span></span><br><span class="line">  &#125;;</span><br><span class="line"> &#125;,</span><br><span class="line"> computed: &#123;</span><br><span class="line"><span class="javascript">  ageval: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">   <span class="keyword">return</span> <span class="keyword">this</span>.info.age;</span></span><br><span class="line">  &#125;</span><br><span class="line"> &#125;,</span><br><span class="line"> watch: &#123;</span><br><span class="line">  ageval: &#123;</span><br><span class="line"><span class="javascript">   handler: <span class="function"><span class="keyword">function</span>(<span class="params">val, oldval</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> that = <span class="keyword">this</span>;</span></span><br><span class="line">    if (val &gt; 0 &amp;&amp; val &lt; 15) &#123;</span><br><span class="line"><span class="javascript">     that.infoMsg = <span class="string">"你还是个小孩"</span>;</span></span><br><span class="line"><span class="javascript">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (val &gt; <span class="number">15</span> &amp;&amp; val &lt; <span class="number">25</span>) &#123;</span></span><br><span class="line"><span class="javascript">     that.infoMsg = <span class="string">"你已经是个少年"</span>;</span></span><br><span class="line"><span class="javascript">    &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">     that.infoMsg = <span class="string">"你已经长大了"</span>;</span></span><br><span class="line">    &#125;</span><br><span class="line">   &#125;,</span><br><span class="line"><span class="javascript">   deep: <span class="literal">true</span></span></span><br><span class="line">  &#125;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>这次我们监听的是计算属性<code>ageval</code>，而计算属性返回的则是<code>info</code>对象中<code>age</code>的值，与第二次的代码进行比较我们可以发现两次代码中监听的一个是对象<code>info</code>，一个是<code>info</code>对象中<code>age</code>的值</p>
</blockquote>
<h2 id="二、计算属性"><a href="#二、计算属性" class="headerlink" title="二、计算属性"></a>二、计算属性</h2><h3 id="2-1-什么是计算属性"><a href="#2-1-什么是计算属性" class="headerlink" title="2.1 什么是计算属性"></a>2.1 什么是计算属性</h3><blockquote>
<p>模板内的表达式非常便利，但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护。例如</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"example"</span>&gt;</span></span><br><span class="line">  &#123;&#123; message.split('').reverse().join('') &#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>遇到复杂逻辑时应该使用Vue特带的计算属性<code>computed</code>来进行处理</p>
</blockquote>
<h3 id="2-2-计算属性的用法"><a href="#2-2-计算属性的用法" class="headerlink" title="2.2 计算属性的用法"></a>2.2 计算属性的用法</h3><blockquote>
<p>在一个计算属性里可以完成各种复杂的逻辑，包括运算、函数调用等，只要最终返回一个结果就可以</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"example"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>Original message: "&#123;&#123; message &#125;&#125;"<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>Computed reversed message: "&#123;&#123; reversedMessage &#125;&#125;"<span class="tag">&lt;/<span class="name">p</span>&gt;</span>　<span class="comment">&lt;!--我们把复杂处理放在了计算属性里面了--&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> vm = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">    el: <span class="string">'#example'</span>,</span><br><span class="line">    data: &#123;</span><br><span class="line">        message: <span class="string">'Hello'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    computed: &#123;</span><br><span class="line">        reversedMessage: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="comment">// `this` 指向 vm 实例</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.message.split(<span class="string">''</span>).reverse().join(<span class="string">''</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>计算属性还可以依赖多个Vue 实例的数据，只要其中任一数据变化，计算属性就会重新执行，视图也会更新</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> @<span class="attr">click</span>=<span class="string">"add()"</span>&gt;</span>补充货物1<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span>总价为：&#123;&#123;price&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> app = <span class="keyword">new</span> Vue(&#123;        </span><br><span class="line">       el: <span class="string">'#app'</span>, </span><br><span class="line">   data: &#123;</span><br><span class="line">       package1: &#123;</span><br><span class="line">           count: <span class="number">5</span>,</span><br><span class="line">           price: <span class="number">5</span></span><br><span class="line">       &#125;,</span><br><span class="line">       package2: &#123;</span><br><span class="line">           count: <span class="number">10</span>,</span><br><span class="line">           price: <span class="number">10</span></span><br><span class="line">       &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    computed: &#123;</span><br><span class="line">     price: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">this</span>.package1.count*<span class="keyword">this</span>.package1.price+<span class="keyword">this</span>.package2.count*<span class="keyword">this</span>.package2.price　　<span class="comment">//总价随着货物或价格的改变会重新计算</span></span><br><span class="line">     &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    methods: &#123;   <span class="comment">//对象的方法</span></span><br><span class="line">        add: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.package1.count++</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<ul>
<li>每一个计算属性都包含一个<code>getter</code> 和一个<code>setter</code> ，我们上面的两个示例都是计算属性的默认用法， 只是利用了<code>getter</code> 来读取</li>
<li>在你需要时，也可以提供一个<code>setter</code> 函数， 当手动修改计算属性的值就像修改一个普通数据那样时，就会触发<code>setter</code> 函数，执行一些自定义的操作，例如</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> vm = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">    el: <span class="string">'#demo'</span>,</span><br><span class="line">    data: &#123;</span><br><span class="line">        firstName: <span class="string">'Foo'</span>,</span><br><span class="line">        lastName: <span class="string">'Bar'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    computed: &#123;</span><br><span class="line">        fullName: &#123;</span><br><span class="line">            <span class="comment">// getter</span></span><br><span class="line">            <span class="keyword">get</span>: function () &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>.firstName + <span class="string">' '</span> + <span class="keyword">this</span>.lastName</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="comment">// setter</span></span><br><span class="line">            <span class="keyword">set</span>: function (newValue) &#123;</span><br><span class="line">                <span class="keyword">var</span> names = newValue.split(<span class="string">' '</span>);</span><br><span class="line">                <span class="keyword">this</span>.firstName = names[<span class="number">0</span>];</span><br><span class="line">                <span class="keyword">this</span>.lastName = names[names.length - <span class="number">1</span>];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//现在再运行 vm.fullName = 'John Doe' 时，setter 会被调用，vm.firstName 和 vm.lastName 也会相应地被更新。</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>绝大多数情况下，我们只会用默认的<code>getter</code> 方法来读取一个计算属性，在业务中很少用到<code>setter</code>,所以在声明一个计算属性时，可以直接使用默认的写法，不必将<code>getter</code> 和<code>setter</code>都声明</p>
</blockquote>
<h3 id="2-3-计算属性缓存"><a href="#2-3-计算属性缓存" class="headerlink" title="2.3 计算属性缓存"></a>2.3 计算属性缓存</h3><blockquote>
<p>除了使用计算属性外，我们也可以通过在表达式中调用方法来达到同样的效果</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;&#123;reverseTitle()&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在组件中</span></span><br><span class="line">methods: &#123;</span><br><span class="line">  reverseTitle: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.title.split(<span class="string">''</span>).reverse().join(<span class="string">''</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>我们可以将同一函数定义为一个方法而不是一个计算属性，两种方式的最终结果确实是完全相同的。只是一个使用<code>reverseTitle()</code>取值，一个使用<code>reverseTitle</code>取值。</li>
<li>然而，不同的是计算属性是基于它们的依赖进行缓存的。计算属性只有在它的相关依赖发生改变时才会重新求值。</li>
<li>这就意味着只要 <code>title</code>还没有发生改变，多次访问<code>reverseTitle</code>计算属性会立即返回之前的计算结果，而不必再次执行函数。</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;&#123;reverseTitle&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;&#123;reverseTitle1()&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> @<span class="attr">click</span>=<span class="string">"add()"</span>&gt;</span>补充货物1<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span>总价为：&#123;&#123;price&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line">    computed: &#123;</span><br><span class="line"><span class="javascript">      reverseTitle: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">          <span class="keyword">return</span> <span class="keyword">this</span>.title.split(<span class="string">''</span>).reverse().join(<span class="string">''</span>)　　<span class="comment">//而使用计算属性，只要title没变，页面渲染是不会重新进这里来计算的，而是使用了缓存。</span></span></span><br><span class="line">      &#125;,</span><br><span class="line"><span class="javascript">      price: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">         <span class="keyword">return</span> <span class="keyword">this</span>.package1.count*<span class="keyword">this</span>.package1.price+<span class="keyword">this</span>.package2.count*<span class="keyword">this</span>.package2.price</span></span><br><span class="line">      &#125;</span><br><span class="line">     &#125;,</span><br><span class="line"><span class="javascript">    methods: &#123;   <span class="comment">//对象的方法</span></span></span><br><span class="line"><span class="javascript">    add: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">this</span>.package1.count++</span></span><br><span class="line">    &#125;,</span><br><span class="line"><span class="javascript">    reverseTitle1: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> <span class="keyword">this</span>.title.split(<span class="string">''</span>).reverse().join(<span class="string">''</span>)　　<span class="comment">//点击补充货物，也会进这个方法，再次计算。不是刷新，而是只要页面渲染，就会进方法里重新计算。</span></span></span><br><span class="line">    &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>相比之下，每当触发重新渲染时，调用方法将总会再次执行函数。 </li>
<li>我们为什么需要缓存？假设我们有一个性能开销比较大的的计算属性 A，它需要遍历一个巨大的数组并做大量的计算。然后我们可能有其他的计算属性依赖于 A </li>
<li>如果没有缓存，我们将不可避免的多次执行 A 的<code>getter</code>！如果你不希望有缓存，请用方法来替代</li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/08/27/vue-component/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/08/28/vue-router/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
